package com.jinly.ryder.common.service.impl;

import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.common.service.SettingItemService;
import com.jinly.ryder.common.service.SystemSettingService;
import com.jinly.ryder.common.service.model.SettingCategory;
import com.jinly.ryder.common.service.model.SettingModel;
import com.jinly.ryder.common.service.model.SystemSetting;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class SystemSettingServiceImpl implements SystemSettingService {

    private final SettingItemService settingItemService;

    private final Validator validator;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSetting(SystemSetting systemSetting) {
        if (systemSetting != null) {
            systemSetting.setName("system");
            settingItemService.saveSettingItem(systemSetting);
        }
    }

    @Override
    public SystemSetting getSetting() {
        SystemSetting systemSetting = new SystemSetting();
        systemSetting.setName("system");
        settingItemService.setSettingItem(systemSetting);
        return systemSetting;
    }

    @Override
    public <T> T getSettingItem(Class<T> tClass) {
        SettingModel settingModel = tClass.getAnnotation(SettingModel.class);
        T value = settingItemService.getItem("system", SettingCategory.SYSTEM, tClass);
        if (value == null) {
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError("缺少配置【" + settingModel.desc() + "】");
        }
        Set<ConstraintViolation<T>> sets = validator.validate(value);
        for (ConstraintViolation<T> set : sets) {
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError(set.getMessage());
        }
        return value;
    }
}
